import ENV_CONFIG from '@/env.js'
import Auth from './permission/index.js';
import { getToken } from './auth.js';
/**
 * 添加cdn域名前缀
 */
export const _cdn = (url = '', cdnurl = '') => {
	if (!url) return '';
	if (url.indexOf('http') === 0) {
		return url;
	}
	if (cdnurl === '') {
		cdnurl = ENV_CONFIG.env.CDN_URL;
	}
	return cdnurl + url;
};
/**
 * 静态资源地址
 */
export const _static = (url = '', staticurl = '') => {
  if (staticurl === '') {
    staticurl = ENV_CONFIG.env.STATIC_URL;
  }
  if (staticurl !== 'local') {
    url = _cdn(url, staticurl);
  }
  return url;
};
/**
 * css背景图片地址
 */
export const _css = (url = '', staticurl = '') => {
  if (staticurl === '') {
    staticurl = ENV_CONFIG.env.STATIC_URL;
  }
  if (staticurl !== 'local') {
    url = _cdn(url, staticurl);
  }
  // #ifdef APP-PLUS
  if (staticurl === 'local') {
    url = plus.io.convertLocalFileSystemURL(url);
  }
  // #endif
  // #ifdef H5
  if (staticurl === 'local') {
    url = `/h5${url}`;
  }
  // #endif
  return `url(${url})`;
}
/**
 * 相册摄像权限校验
 */
async function auths(){
	return new Promise(async (resolve, reject) => {
		// #ifdef MP
		let authState = 0;
		authState += await new Auth('writePhotosAlbum').check();
		if (authState < 1) return;
		authState += await new Auth('camera').check();
		if (authState < 2) return;
		// #endif
		// #ifdef APP
		let authState = 0;
		authState += await this.$store.dispatch('permission/requestPermissions', 'writePhotosAlbum')
		if (authState < 1) return;
		authState += await this.$store.dispatch('permission/requestPermissions', 'camera')
		if (authState < 2) return;
		// #endif
		resolve(true)
	});
}
/**
 * 上传文件到服务器
 * @param {Object} filePath 文件路径
 */
function upload(filePath){
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: ENV_CONFIG.env.UPLOAD_URL,
			filePath,
			name: 'file',
			header: {
				token: getToken()
			},
			success:(res)=> {
				uni.hideLoading()
				if (res.statusCode == 200) {
					resolve(JSON.parse(res.data));
				} else {
					resolve(JSON.parse(res.data));
				}
			},
		})
	})
}
/**
 * 上传图片
 */
export const _uploadImg = async (count=9) => {
	await auths()
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success:async (res) =>{
				uni.showLoading({
					title: '上传中...'
				})
				resolve(await upload(res.tempFilePaths[0])) 
			}
		});

	});
}
/**
 * 上传视频
 */
export const _uploadVideo = (url, name, type) => {
	auths()
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			sourceType: ['camera', 'album'],
			success: async res => {
				if (res.tempFile.size >= 10 * 1024 * 1024){
					uni.$u.toast('视频不能大于10M')
					reject('视频不能大于10M')
					return
				} 
				resolve(await upload(res.tempFilePath))
			}
		});
	});
}
/**
 * 上传文件
 */
export const _uploadFile = ()=>{
	return new Promise((resolve, reject) => {
		// #ifdef H5
		uni.chooseFile({
			count:1,
			extension:['.text','.pdf','.doc','.docx','.xls'],
			success: async(res) =>{
				if(res.errMsg=='chooseFile:ok'){
					resolve(await upload(res.tempFiles[0].path))
				}
			}
		})
		// #endif
		// #ifdef MP-WEIXIN | MP-QQ
		uni.chooseMessageFile({
			type: 'file',
			success:async(res)=> {
				if (res.tempFiles[0].type != 'file') {
					uni.showToast({
						title: '请选择文件类型上传',
						icon: 'none'
					})
					resolve(false)
					return
				}
				resolve(await upload(res.tempFiles[0].path))
			}
		})
		// #endif
	})
}
/**
 * 文件下载
 */
export class downFile{
	constructor(url,fileName,_this=this) {
		this._this=_this
		this.url = url
		this.fileName = fileName
	}
	async down(){
		// #ifdef APP
		const _this = this._this
		const aut = await _this.$store.dispatch('permission/requestPermissions','writePhotosAlbum')
		if(aut !=1)return
		// #endif
		uni.showLoading({
			title:'正在下载，请稍等...',
			mask:true
		})
		const downloadTask = await netDownFile()
		if(!downloadTask) {
			uni.$u.toast('下载失败，请稍后再试')
			return uni.hideLoading()
		}
		if(this.isImg()){
			// 图片保存到手机相册
			uni.saveImageToPhotosAlbum({
				filePath: downloadTask,
				success: function () {
					uni.$u.toast('文件下载成功')
				},
				fail: function() {
					uni.$u.toast('文件下载失败')
				}
			});
		}else if(this.isVideo()){
			//保存视频到相册
			uni.saveVideoToPhotosAlbum({
				filePath: downloadTask,
				success: function () {
					uni.$u.toast('文件下载成功')
				},
				fail: function() {
					uni.$u.toast('文件下载失败')
				}
			});
		}else {
			//#ifdef APP-PLUS
			const osname = plus.os.name
			uni.saveFile({
				tempFilePath:downloadTask,
				success:(res)=>{
					if (osname == 'Android') {
						this.fSetFileName()
					}else{
						uni.openDocument({
							filePath:res.savedFilePath,
						})
					}
				}
			})
			//#endif
			//#ifdef MP-WEIXIN
			const FileSystemManager = wx.getFileSystemManager();
			FileSystemManager.saveFile({
				tempFilePath:downloadTask,
				success:(res)=>{
					if(res.errMsg != 'saveFile:ok'){
						uni.showToast({
							title: '文件保存失败'
						})
						return
					}
					if (uni.getSystemInfoSync().platform === 'android') {
						uni.showModal({
							title:"保存地址为",
							content:"手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles"
						})
					} else {
						uni.showToast({
							title:"抱歉IOS暂不支持",
							icon:"none"
						})
					}
				}
			})
			//#endif
			// #ifdef H5
				const createA = document.createElement("a");
				createA.download = this.fileName;
				createA.href = this.url;
				document.body.appendChild(createA);
				createA.click();
				createA.remove();
			// #endif
		}
		uni.hideLoading()
	}
	/**
	 * 文件下载
	 */
	netDownFile(){
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url:this.url,
				success: res=>{
					if (res.statusCode === 200) {
						resolve(res.tempFilePath)
					}else{
						uni.showToast({
							title: '文件下载失败'
						})
						resolve(false)
					}
				}
			})
		}) 
	}
	/**
	 * APP文件保存重命名
	 * @param {Object} sFilePath 文件
	 * @param {Object} sFileName 文件名
	 */
	fSetFileName(sFilePath, sFileName) {
		//saveFile API保存的本地地址
		const url = this.url;//下载地址
		const dtask = plus.downloader.createDownload(url,{
			filename: `file://storage/emulated/0/${ENV_CONFIG.APP_TITLE_ZH}/${sFileName}`,
		},
		(d, status) =>{
			if (status == 200) {
				let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
				uni.$u.toast(`已保存到文件夹：/${ENV_CONFIG.APP_TITLE_ZH}/${sFileName}`)
				setTimeout(()=>{
					plus.runtime.openFile(d.filename); //选择软件打开文件
				},1500)
			} else {
				//下载失败
				plus.downloader.clear(); //清除下载任务
				uni.showToast({
					title:'文件下载失败',
					icon:'error'
				})
			}
		})
		dtask.start();
	}
	/**
	 * 判断是否图片类型
	 */
	isImg(){
		const url = this.url
		return url.substring(url.length - 3) == "jpg" || url.substring(url.length - 3) == "png"
	}
	/**
	 * 判断是否视频类型
	 */
	isVideo(){
		const url = this.url
		return url.substring(url.length - 3) == "MP4" || url.substring(url.length - 3) == "mp4"
	}
}
